<script setup>
import Toolbar from "@/components/Toolbar.vue";
import { onMounted, ref } from "vue";
import {
  getUserListPage,
  addUser,
  editUser,
  delUser,
} from "@/apis/user";
import { getDepartmentTree } from "@/apis/department";
import util from "@/utils/date.js";
import { getButtonList } from "@/utils/index";
import { useUserStore } from "@/stores/userStore";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getRoleList } from "@/apis/role";

const route = useRoute();
const userStore = useUserStore();

// 当前登录用户拥有的按钮列表
const buttonList = getButtonList(route.path, userStore.userMenuPermissions);
// 用户列表
const userList = ref([]);
// 单位数据集合
const options = ref([]);
// 角色列表
const roles = ref([]);
// form引用
const ruleFormRef = ref(null);
// 添加和编辑区分标记
let isEdit = ref(false);
// 获取用户列表
const getUserList = async () => {
  const res = await getUserListPage(parms.value);
  console.log(res);
  parms.value.total = res.dataCount;
  userList.value = res.data;
};
// 获取部门列表
const getDepartment = async () => {
  const res = await getDepartmentTree({ pid: 0 });
  // console.log(res);
  options.value.push(res);
};

// 获取角色列表
const getRoles = async () => {
  const res = await getRoleList();
  // console.log(res);
  roles.value = res.data;
};

// 格式化时间
const formatBirth = (row) => {
  return !row.birth || row.birth == ""
    ? ""
    : util.formatDate.format(new Date(row.birth), "yyyy-MM-dd");
};
// 请求数据列表参数
const parms = ref({
  page: 0,
  pageSize: 15,
  currentPage: 1,
  total: 0,
  key: "",
});
// 点击按钮事件
const buttonClick = (item) => {
  // console.log(item);
  parms.value.key = item.search;
  if (item.func == "handleAdd") {
    isEdit.value = false;
    handleAdd();
  } else if (item.func == "handleEdit") {
    handleEdit();
    isEdit.value = true;
  } else if (item.func == "handleDel") {
    handleDelete();
  } else if (item.func == "getUsers") {
    getUserList();
  }
};
// 表格id
const tableRef = ref(null);
// 当前选择行
const currentRow = ref(null);

const selectRow = (selection, row) => {
  console.log(selection, row);
  currentRow.value = null;
  tableRef.value.clearSelection();
  if (selection.length == 0) {
    return;
  }
  if (row) selectCurrentRow(row);
};
// 点击行勾选复选框
const selectCurrentRow = (val) => {
  // console.log(val);
  currentRow.value = val;
  tableRef.value.clearSelection();
  tableRef.value.toggleRowSelection(val, true);
};

onMounted(async () => {
  getUserList();
  getDepartment();
  getRoles();
});

// 显示添加弹框标记
const showDialogForm = ref(false);
// 添加/编辑表单数据
let dialogForm = ref({
  id: 0,
  riDs: [],
  realName: "",
  loginName: "",
  loginPwd: "",
  dids: [],
  sex: 0,
  age: 0,
  birth: "",
  address: "",
  departmentId: 0,
});
const rules = ref({
  realName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  loginName: [{ required: true, message: "请输入登录名称", trigger: "blur" }],
  loginPwd: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
});
// 点击添加按钮弹框form表单
const handleAdd = async () => {
  dialogForm.value = {
    id: 0,
    riDs: [],
    realName: "",
    loginName: "",
    loginPwd: "",
    dids: [],
    sex: 0,
    age: 0,
    birth: "",
    address: "",
    departmentId: 0,
  };
  showDialogForm.value = true;
};
// 编辑弹框
const handleEdit = async () => {
  if (currentRow.value) {
    dialogForm.value = Object.assign({}, currentRow.value);
    showDialogForm.value = true;
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// 提交表单
const submitForm = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      // dialogForm.value.birth =
      //   !dialogForm.value.birth || dialogForm.value.birth == ""
      //     ? util.formatDate.format(new Date(), "yyyy-MM-dd")
      //     : util.formatDate.format(
      //         new Date(dialogForm.value.birth),
      //         "yyyy-MM-dd"
      //       );
      if (dialogForm.value.birth)
        dialogForm.value.birth = util.formatDate.format(
          dialogForm.value.birth,
          "yyyy-MM-dd"
        );
      dialogForm.value.departmentId = dialogForm.value.dids.pop();
      let msg = "添加成功";
      if (isEdit.value) {
        await editUser(dialogForm.value);
        msg = "编辑成功";
      } else {
        await addUser(dialogForm.value);
      }
      ElMessage.success(msg);
      parms.value.page = 0;
      parms.value.currentPage = 1;
      getUserList();
      resetForm();
    } else {
      console.error("error submit", fields);
    }
  });
};

// 取消表单
const resetForm = () => {
  showDialogForm.value = false;
  ruleFormRef.value.clearValidate();
  ruleFormRef.value.resetFields();
};

// 删除
const handleDelete = async () => {
  if (currentRow.value) {
    ElMessageBox.confirm("确定要删除吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await delUser({ id: currentRow.value.id });
        ElMessage.success("删除成功");
        getUserList();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled",
        });
      });
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// 分页改变
const handleCurrentChange = (page) => {
  // console.log(page);
  parms.value.page = page;
  parms.value.currentPage = page;
  getUserList();
};
</script>

<template>
  <section>
    <!-- 工具条 -->
    <Toolbar :button-list="buttonList" @call-function="buttonClick"></Toolbar>

    <!-- 列表 -->
    <el-table :data="userList" border @select="selectRow" @row-click="selectCurrentRow" ref="tableRef">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column type="index" width="80" label="序号"></el-table-column>
      <el-table-column prop="realName" label="昵称" sortable></el-table-column>
      <el-table-column prop="loginName" label="登录名" sortable></el-table-column>
      <el-table-column prop="roleNames" label="角色" sortable>
        <template #default="{ row }">
          <el-tag v-for="(item, index) in row.roleNames" :key="index">
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="departmentName" label="所属部门" sortable></el-table-column>
      <el-table-column prop="sex" label="性别" sortable>
        <template #default="{ row }">
          <el-tag :type="row.sex == 1 ? 'success' : 'danger'">
            {{ row.sex == 1 ? "男" : "女" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="birth" label="生日" :formatter="formatBirth" sortable></el-table-column>
      <el-table-column prop="status" label="状态" width="" sortable>
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'success' : 'danger'" disable-transitions>{{ scope.row.status == 0 ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="parms.pageSize" :total="parms.total"
                     :current-page="parms.currentPage" style="float: right">
      </el-pagination>
    </el-col>
    <!-- 新增编辑界面 -->
    <el-dialog v-model="showDialogForm" :title="isEdit == true ? '编辑用户' : '添加用户'" :close-on-click-modal="false" @close="resetForm">
      <el-form ref="ruleFormRef" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon :model="dialogForm">
        <el-form-item label="昵称" prop="realName">
          <el-input v-model="dialogForm.realName" />
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="dialogForm.loginName" />
        </el-form-item>
        <el-form-item label="角色" prop="rids" v-show="isEdit">
          <el-select multiple v-model="dialogForm.riDs" placeholder="请选择角色">
            <el-option :key="0" :label="'未选择角色'" :value="0"></el-option>
            <el-option v-for="item in roles" :key="item.Id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-show="!isEdit" prop="loginPwd">
          <el-input show-password v-model="dialogForm.loginPwd" />
        </el-form-item>
        <el-form-item label="部门" prop="dids">
          <el-cascader v-model="dialogForm.dids" :options="options" style="width: 100%" :props="{ checkStrictly: true, expandTrigger: 'hover' }" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="dialogForm.sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="dialogForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="生日" prop="birth">
          <el-date-picker type="date" placeholder="选择日期" v-model="dialogForm.birth"></el-date-picker>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="dialogForm.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </section>
</template>
<style lang="scss" scoped>
.el-tag {
  margin-right: 5px;
}
.el-pagination {
  margin-top: 10px;
}
</style>